import hashlib
import math
import os
from io import BytesIO

import requests
from django.conf import settings
from django.core.paginator import Paginator
from django.db import connection
from django.db.models import Count
from django.http import HttpResponse
from django.shortcuts import render, redirect

# Create your views here.
from django.utils import timezone

from post.models import *


from PIL import Image, ImageDraw, ImageFont
import random
import string


def get_text(number):
    """
    生成随机字符串
    :param number: 需要生成的字符的个数
    :return: 字符串
    """

    source = string.digits + string.ascii_uppercase
    # source = "01234....XYZ"
    return "".join((random.sample(source, number)))


def draw_line(draw, size, color="#0000FF", num=5):
    """
    生成随机干扰线
    :param draw:
    :param size:图片的大小（width,height）
    :param color:干扰线的颜色，默认为蓝色
    :param num: 干扰线的数量，默认为5条
    :return:
    """
    for i in range(num):
        begin = (random.randint(0, size[0] * 0.25), random.randint(0, size[1]))
        end = (random.randint(size[0] * 0.75, size[0]), random.randint(0, size[1]))
        draw.line([begin, end], fill=color, width=3)


def draw_point(draw, size, chance=0.7):
    """
    生成随机干扰点
    :param draw:
    :param size: 图片大小
    :param chance: 生成干扰点的概率，默认为0.7
    :return:
    """
    for w in range(size[0]):
        for h in range(size[1]):
            if chance >= random.randint(0, 1):
                draw.point((w, h), fill=(0, 0, 255))


def draw_image(size=(200, 50), number=4, fontcolor="#0000FF", ground_color="#FFFFFF"):
    """
    生成图片
    :param size: 图片大小，默认为200像素宽，50像素高
    :param number: 文字数量，默认为6个
    :param fontcolor: 文字颜色。默认为蓝色
    :param ground_color: 背景色，默认为白色
    :return:
    """
    width, height = size
    # 生成图片
    image = Image.new("RGB", size, ground_color)
    # 生成一个RGB模式，大小为size，背景色为ground_color的图片

    # 设置字体
    font = ImageFont.truetype("./static/fonts/arial.ttf", int(size[1] * 0.8))
    # 字体为arial.ttf 大小为图片高度的0.8倍

    # 创建画笔
    draw = ImageDraw.Draw(image)

    # 生成文字
    text = get_text(number)
    # print(text)
    # 获取文字的长度和高度
    font_width, font_height = font.getsize(text)
    # 填充文字
    draw.text(((width - font_width) / number, (height - font_height) / number), text, font=font, fill=fontcolor)
    # 生成干扰线
    # draw_line(draw, size)
    # 生成噪点
    draw_point(draw, size)
    # 保存图片
    return image,text
    # save_path = os.path.join(settings.BASE_DIR, 'static', 'img', 'a.jpg')
    # image.save(save_path)
    # return text

class IndexView:
    def get(self, num=1):
        if not self.session.get('info'):
            return redirect('/')
        num = int(num)
        postlist = Post.objects.all().order_by('-created')
        # 创建分页器对象
        page_a = Paginator(postlist, 2)
        # 获取某一页数据
        page_post = page_a.page(num)
        # 获取每一页显示页码数列
        begin_ = num - 5
        if begin_ < 1:
            begin_ = 1
        end_ = begin_ + 9
        if end_ > page_a.num_pages:
            end_ = page_a.num_pages
        if end_ < 10:
            begin_ = 1
        else:
            begin_ = end_ - 9
        page_list = range(begin_, end_ + 1)
        return render(self, 'index.html', {'postlist': page_post, 'page_list': page_list,
                                           'currentNum': num})

class Detailview:
    b=0
    def get(self,postid):
        if not self.session.get('info'):
            return redirect('/')
        current_time = timezone.now()
        postid = int(postid)
        Detailview.b=postid
        post_obj = Post.objects.get(id=postid)
        cursor = connection.cursor()
        query = "SELECT * FROM t_comment WHERE title =%s"
        # 执行查询语句，传入参数值
        cursor.execute(query, (post_obj.title,))
        data = cursor.fetchall()
        count = like.objects.filter(title=post_obj.title).count()
        context = {
            'post': post_obj,
            'data': data,
            'count':count
        }
        if not self.session.get('info'):
            return redirect('/')
        if self.method == "GET":
            return render(self, 'detail.html',context)
        else:
            content=self.POST.get('comment')
            cursor = connection.cursor()
            cursor.execute("SELECT nick_name FROM t_user WHERE username =%s", (self.session.get('info'),))
            author=cursor.fetchall()[0][0]
            sql = "INSERT INTO t_comment (author, date_at, content,title) VALUES (%s, %s,%s,%s)"
            values = (author, current_time,content,post_obj.title)
            cursor.execute(sql, values)
            return render(self, 'detail.html',context)
    def good(self):
        stream=BytesIO()
        post_obj = Post.objects.get(id=Detailview.b)
        title=post_obj.title
        cursor = connection.cursor()
        cursor.execute("SELECT nick_name FROM t_user WHERE username =%s", (self.session.get('info'),))
        author = cursor.fetchall()[0][0]
        try:
            a = list(self.GET.keys())[0]
            record=like.objects.filter(author=author, title=title)
            if record.exists():
                record.delete()
                with open('static/img/good.png', 'rb') as f:
                    img = Image.open(f)
                    # 将图片保存到内存流中
                    img.save(stream, 'png')
                    # 返回内存流的数据
                response = HttpResponse(stream.getvalue())
                return response
            else:
                like.objects.create(author=author,title=title,aa=True)
                with open('static/img/goodone.png', 'rb') as f:
                    img = Image.open(f)
                    # 将图片保存到内存流中
                    img.save(stream, 'png')
                # 返回内存流的数据
                response = HttpResponse(stream.getvalue())
                return response
        except IndexError:
            if like.objects.filter(author=author, title=title).exists():
                with open('static/img/goodone.png', 'rb') as f:
                    img = Image.open(f)
                    # 将图片保存到内存流中
                    img.save(stream, 'png')
                    # 返回内存流的数据
                response = HttpResponse(stream.getvalue())
                return response
            else:
                with open('static/img/good.png', 'rb') as f:
                    img = Image.open(f)
                    # 将图片保存到内存流中
                    img.save(stream, 'png')
                # 返回内存流的数据
                response = HttpResponse(stream.getvalue())
                return response
    def collect_one(self):
        stream=BytesIO()
        post_obj = Post.objects.get(id=Detailview.b)
        title=post_obj.title
        cursor = connection.cursor()
        cursor.execute("SELECT nick_name FROM t_user WHERE username =%s", (self.session.get('info'),))
        author = cursor.fetchall()[0][0]
        try:
            a = list(self.GET.keys())[0]
            record=Collect.objects.filter(author=author, title=title)
            if record.exists():
                record.delete()
                with open('static/img/collect.png', 'rb') as f:
                    img = Image.open(f)
                    # 将图片保存到内存流中
                    img.save(stream, 'png')
                    # 返回内存流的数据
                response = HttpResponse(stream.getvalue())
                return response
            else:
                Collect.objects.create(author=author,title=title)
                with open('static/img/collectone.png', 'rb') as f:
                    img = Image.open(f)
                    # 将图片保存到内存流中
                    img.save(stream, 'png')
                # 返回内存流的数据
                response = HttpResponse(stream.getvalue())
                return response
        except IndexError:
            if Collect.objects.filter(author=author, title=title).exists():
                with open('static/img/collectone.png', 'rb') as f:
                    img = Image.open(f)
                    # 将图片保存到内存流中
                    img.save(stream, 'png')
                    # 返回内存流的数据
                response = HttpResponse(stream.getvalue())
                return response
            else:
                with open('static/img/collect.png', 'rb') as f:
                    img = Image.open(f)
                    # 将图片保存到内存流中
                    img.save(stream, 'png')
                # 返回内存流的数据
                response = HttpResponse(stream.getvalue())
                return response





def getPostbyCid(request, categoryid):#归档界面
    if not request.session.get('info'):
        return redirect('/')
    categoryid = int(categoryid)
    c_post = Post.objects.filter(category_id=categoryid)
    return render(request, 'postlist.html', {'c_post': c_post})


def getcollect(request):#收藏界面
    if not request.session.get('info'):
        return redirect('/')
    cursor = connection.cursor()
    cursor.execute("SELECT nick_name FROM t_user WHERE username =%s", (request.session.get('info'),))
    author = cursor.fetchall()[0][0]
    title = Collect.objects.filter(author=author).values_list('title', flat=True)
    c_post=[]
    if title:
        for i in list(title):
            c_post.append(Post.objects.filter(title=i))
        return render(request, 'collect.html',{'c_post': c_post})
    else:
        return render(request, 'collect.html')




def getPostbycreated(request, year=1, month=1):
    if not request.session.get('info'):
        return redirect('/')
    year = int(year)
    month = int(month)
    if year == 1 and month == 1:
        c_post = Post.objects.all().order_by('-created')
    else:
        c_post = Post.objects.filter(created__year=year, created__month=month)

    return render(request, 'postlist.html', {'c_post': c_post})


def index(request):
    if request.method == 'POST':
        url = "https://api.seniverse.com/v3/weather/daily.json?key=SRvR8i7oAxmQ5zU8-&location=" + request.POST[
            'city'] + "&language=zh-Hans&unit=c&start=-1&days=5"
    else:
        url = "https://api.seniverse.com/v3/weather/daily.json?key=SRvR8i7oAxmQ5zU8-&location=太原&language=zh-Hans&unit=c&start=-1&days=5"
    data = requests.get(url).json()
    weather = data["results"]
    city = weather[0]["location"]["name"]
    context = {
        "city": city,
        "list": weather[0]["daily"]
    }
    return render(request, 'weather.html', context)


def test_one(request):
    if not request.session.get('info'):
        return redirect('/')
    return render(request, 'weichat.html')

def img_code(request):
    image_object,code_str=draw_image()
    stream=BytesIO()
    image_object.save(stream,'png')
    request.session['image_code']=code_str
    request.session.set_expiry(240)
    return HttpResponse(stream.getvalue())



def login(request):
    if request.method == "GET":
        return render(request, 'login.html')
    else:
        username_ = request.POST.get('user')
        passwd = request.POST.get('pwd')
        check=request.POST.get('check')
        image_code=request.session.get('image_code')
        if image_code==check:
            pass
        else:
            return HttpResponse("验证码过期或失败")
        #加密
        m = hashlib.md5()
        m.update(passwd.encode("utf8"))
        pwd_data = m.hexdigest()
        #结束
        cursor = connection.cursor()
        cursor.execute("SELECT password FROM t_user WHERE username = %s", (username_,))
        password= cursor.fetchall()
        if password:
            if pwd_data==password[0][0]:
                request.session["info"]=username_
                return redirect('/index')
            else:
                return render(request,'login.html',{'text':'用户名或密码错误'})
        else:
            return render(request,'login.html',{'text':'用户名错误'})


def register(request):
    if request.method == "GET":
        return render(request, 'register.html')
    else:
        username = request.POST.get('user')
        passwd = request.POST.get('pwd')
        nick_name = request.POST.get('nick_name')
        #先往数据库中查找 邮箱不能一样 数据库中没有才允许注册
        data=User.objects.filter(username=username)
        if data:
            return HttpResponse("用户已经存在，注册失败")
        else:
            # 使用md5算法加密 数据库存储密文
            m = hashlib.md5()
            m.update(passwd.encode("utf8"))
            pwd_data = m.hexdigest()

            h = User()
            h.nick_name = nick_name
            h.password = pwd_data
            h.username = username
            h.save()
            return HttpResponse("congratulations!注册成功")

def logout(request):
    if request.method == "GET":
        return render(request, 'logout.html')
    else:
        username_ = request.POST.get('user')
        passwd = request.POST.get('pwd')
        # 加密
        m = hashlib.md5()
        m.update(passwd.encode("utf8"))
        pwd_data = m.hexdigest()
        # 结束
        cursor = connection.cursor()
        cursor.execute("SELECT password FROM t_user WHERE username = %s", (username_,))
        password = cursor.fetchall()
        if password:
            if pwd_data == password[0][0]:
                cursor.execute("DELETE FROM t_user WHERE username =%s",(username_,))
                return render(request, 'logout.html',{"text":"注销成功"})
            else:
                return render(request, 'logout.html', {"text": "用户名或密码错误"})
        else:
            return render(request, 'logout.html', {"text": "用户名错误"})



